<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/6/30
 * Time: 10:47
 */

namespace Biz\module\Classes;

use Biz\cache\GoodsHistory as cGoodsHistory;
use Biz\pockets\serviceTrait\_Async;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\service\GoodsDetail as sGoodsDetail;
use Medoo\Medoo;
use Biz\service\Goods as sGoods;

class GoodsHistory
{

    use _Async;

    public static function addBrowseHistory($uid, $goodsId)
    {
        return cGoodsHistory::addBrowseHistory($uid, $goodsId);
    }

    public static function remBrowseHistory($uid, $agoTime = '-7 days')
    {

        self::_async($uid, $agoTime);
    }

    public static function _async_remBrowseHistory($uid, $agoTime = '-7 days')
    {

        cGoodsHistory::remBrowseHistory($uid, $agoTime);
    }

    public static function getNearGoodsBrowseList($uid, $nearDay = 7, $page = 1, $pageSize = 20)
    {
        $nowTime = time();
        $startTime = strtotime('-7 days');
        $zsetKey = cGoodsHistory::getBrowseKey($uid);
        $result = ['list'=>[],'is_over'=>0];

        $total = cGoodsHistory::zcount($zsetKey, $startTime, $nowTime);

        $totalPage = ceil($total / $pageSize);

        $page = ($page <= $totalPage) ? $page : $totalPage;

        $start = ($page - 1) * 20;

        $stop = $page * 20 - 1;


        $goodsIds = cGoodsHistory::zrevrange($zsetKey, $start, $stop,'withscores');


        if (empty($goodsIds)) {
            return $result;
        }


        $list = sGoods::goods(array_keys($goodsIds));


        if(!empty($list)){
            $list = array_map(function($v) use($goodsIds){

                $v['addtime'] = $goodsIds[$v['id']];

                return $v;

            },$list);
        }

        return [
            'list'    => array_values($list),
            'is_over' => ($page == $totalPage) ? 1 : 0
        ];
    }

}